import json

from sys_manager.models import PermissionsModel
from django_redis import get_redis_connection


def redis_storage_permissions(user):

    '''

    把当前用户的权限信息缓存到Redis数据库中

    Redis中存放数据的结构为： user_用户id--->字典{key:path  value[列表]}
    :param user:
    :return:
    '''

    permission_ids=user.roles.values_list('permissions',flat=True).distinct()

    permissions=PermissionsModel.objects.filter(is_menu=False,id__in=permission_ids).values('id','name','method','path')

    if not permissions.exists():
        return

    permission_dict={}

    for permission in permissions:

        method=str(permission.get('method')).replace('\u200b','')
        path = str(permission.get('path')).replace('\u200b', '')
        _name= str(permission.get('name')).replace('\u200b', '')
        _id=permission.get('id')

        if path in permission_dict:

            permission_dict[path].append({
                'method':method,
                'name': _name,
                'id':_id

            })

        else:

            permission_dict[path]=[{

                'method': method,
                'name': _name,
                'id': _id
            }]

    for key in permission_dict:
        permission_dict[key]=json.dumps(permission_dict[key])

    #存放到redis中

    redis_conn=get_redis_connection('default')
    redis_conn.hmset(f'user_{user.id}',permission_dict)
